/*
 * 作者:熊猫
 * 日期:2017 - 3 - 19 10 - 2 - 22
 *
 */

package net.lainiao.other.CodeStatic;

import com.sun.org.apache.bcel.internal.classfile.Code;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.RecursiveTask;

/**
 * Created by Administrator on 2017/3/19.
 */
public class CodeTask extends RecursiveTask<Integer> {
    private File file;

    public CodeTask(File file) {
        this.file = file;
    }

    @Override
    protected Integer compute() {
        int res=0;
        if(file.isDirectory()){
            String dirName=file.getName();
            if(dirName.equals("target")){
                return 0;
            }
            File[] files=file.listFiles();
            List<CodeTask> tasks=new ArrayList<>();
            for(File temFile : files){
                CodeTask codeTask=new CodeTask(temFile);
                tasks.add(codeTask);
            }
            invokeAll(tasks);
            for(CodeTask task:tasks){
                try {
                    res+=task.get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        }
        else{
            if(file.getName().endsWith(".java")){
                System.out.println(file.getAbsolutePath());
                res=ReadFile();
            }
        }
        return res;
    }

    //读取文件
    private int ReadFile() {
        int res=0;
        FileReader fileReader;
        BufferedReader bufferedReader;
        try {
            fileReader=new FileReader(file);
            bufferedReader=new BufferedReader(fileReader);
            String line=null;
            while((line=bufferedReader.readLine())!=null){
                line=line.trim();
                if(line.equals("")||line.length()==0){
                    continue;
                }
                if(line.startsWith("*")||line.startsWith("/")){
                    continue;
                }
                if(line.startsWith("package")){
                    continue;
                }
                if(line.startsWith("import")){
                    continue;
                }
                res++;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        finally {
            return res;
        }
    }
}
